package com.kfm.web.controller.system;

import com.kfm.common.domain.entity.User;
import com.kfm.common.domain.response.Result;
import com.kfm.common.domain.model.LoginUser;
import com.kfm.common.util.RSAUtils;
import com.kfm.common.util.SecurityUtils;
import com.kfm.system.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class SysUserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录方法
     *
     * @param map     请求参数，包含用户名和密码
     * @param request HTTP请求对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        // if (!CaptchaUtil.ver(map.get("captcha"), request)) {
        //     CaptchaUtil.clear(request);
        //     return Result.failure("验证码错误");
        // }
        // CaptchaUtil.clear(request);
        // 按照前端携带的 uuid 查询私钥
        String uuid = map.get("uuid");
        String privateKey = redisTemplate.opsForValue().get(uuid);
        redisTemplate.delete(uuid); // 删除 redis 中存储的私钥
        // 使用私钥解密密码
        String password = RSAUtils.decrypt(privateKey, map.get("password"));
        // 手动调用 SecurityUtils 的登录校验方法
        LoginUser loginUser = SecurityUtils.login(map.get("username"), password, authenticationManager);
        return Result.success("登录成功", loginUser.getToken());
    }

    /**
     * 注册
     *
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String password = map.get("password");
        String repass = map.get("repass");
        if (password == null || !password.equals(repass)) {
            return Result.failure("两次密码不一致");
        }
        String username = map.get("username");
        if (username == null || username.isEmpty()) {
            return Result.failure("用户名为空");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(map.get("phone"));
        int insert = userService.insertSelective(user);
        return insert > 0 ? Result.success("注册成功", null) : Result.failure("注册失败");
    }

    @RequestMapping("/list")
    // 表示登录的用户 必须具备 user:list 权限才能访问 或者 具备 ROLE_admin 角色就能访问
    @PreAuthorize("hasAuthority('user:list') or hasRole('ROLE_admin')")
    public Result list() {
        List<User> users = userService.selectAll();
        return users == null ? Result.failure("查询失败") : Result.success("查询成功", users);
    }

    @PostMapping("/edit")
    @PreAuthorize("hasAuthority('user:edit') or hasAnyRole('ROLE_admin')")
    public Result edit(@RequestBody User user) {
        int i = userService.updateByPrimaryKeySelective(user);
        return i > 0 ? Result.success("修改成功") : Result.failure("修改失败");
    }

    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('user:delete') or hasAnyRole('ROLE_admin')")
    public Result delete(@PathVariable("id") Integer id) {
        int i = userService.deleteByPrimaryKey(id);
        return i > 0 ? Result.success("删除成功") : Result.failure("删除失败");
    }
}
